﻿using System;
using System.Collections.Generic;
using NVelocity.App;
using NVelocity;
using System.IO;
using Commons.Collections;

namespace Liberate.CodeGenerator
{
    static class VelocityUtils
    {
        private static readonly IDictionary<string, VelocityEngine> engines = new Dictionary<string, VelocityEngine>();

        public static VelocityEngine GetEngine(string templateBasePath)
        {
            if (string.IsNullOrEmpty(templateBasePath))
            {
                return null;
            }
            templateBasePath = templateBasePath.ToLower();
            VelocityEngine engine;
            engines.TryGetValue(templateBasePath, out engine);
            if (engine == null)
            {
                engine = new VelocityEngine();
                var props = new ExtendedProperties();
                props.AddProperty("file.resource.loader.path", templateBasePath);
                engine.Init(props);
                engines[templateBasePath] = engine;
            }
            return engine;
        }

        public static Template GetTemplate(string templateBasePath, string templateFile)
        {
            var engine = GetEngine(templateBasePath);
            if (engine == null) return null;
            var vlTemplate = engine.GetTemplate(templateFile);
            if (vlTemplate == null)
                throw new ArgumentException(string.Format("未能创建NVelocity模板：{0}", templateFile));
            return vlTemplate;
        }

        public static void Merge(Template template,
            IDictionary<string, object> properties,
            string targetFile)
        {
            //创建目录
            var dir = Path.GetDirectoryName(targetFile);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            using (var sw = new StreamWriter(targetFile))
            {
                Merge(template, properties, sw);
            }
        }

        public static void Merge(Template template,
            IDictionary<string, object> properties,
            TextWriter writer)
        {
            var vlContext = new VelocityContext();
            foreach (var pair in properties)
            {
                //把TemplateFile里定义的property加进来
                vlContext.Put(pair.Key, pair.Value);
            }
            template.Merge(vlContext, writer);
        }
        public static string Eval(VelocityEngine engine, IDictionary<string, object> properties, string inString)
        {
            var vlContext = new VelocityContext();
            foreach (var pair in properties)
            {
                //把TemplateFile里定义的property加进来
                vlContext.Put(pair.Key, pair.Value);
            }
            var sw = new StringWriter();
            engine.Evaluate(vlContext, sw, "Eval", inString);
            return sw.ToString();
        }
    }
}
